var M = {};

M.checkLoginForm = function(){
	var form = $('#loginForm'),
		email_el = $('[name=email]', form),
		pass_el = $('[name=password]', form),
		err_el = $('.err', form);
	err_el.removeClass('show').html('<span class="icon-err"></span>');
	if(form.data('check')){
		return true;
	}
	if(!email_el.val()){
		err_el.append(TVB.MError.email.empty+'<br />').addClass('show');
	}else if(!isValidEmail(email_el.val())){
		err_el.append(TVB.MError.email.illegal+'<br />').addClass('show');
	}
	if(!pass_el.val()){
		err_el.append(TVB.MError.pwd.illegal+'<br />').addClass('show');
	}else if(pass_el.val().length < 6){
		err_el.append(TVB.MError.pwd.illegal+'<br />').addClass('show');
	}
	if(err_el.hasClass('show')){
		return false;
	}
	form.data('check', 1).submit();
};
M.checkUserInfoForm = function(){
	var form = $('#uInfoForm'), url=$('.next', form).attr('ajax'),
		email_el = $('[name=a_email]', form),
		pass_el = $('[name=password]', form),
		repass_el = $('[name=repassword]', form),
		err_el = $('.err-msg', form);
	err_el.html('').addClass('hidden');
	if(form.data('check')){
		return true;
	}
	if(!email_el.val()){
		err_el.append('<div>* '+TVB.MError.email.empty+'</div>').removeClass('hidden');
	}else if(!isValidEmail(email_el.val())){
		err_el.append('<div>* '+TVB.MError.email.illegal+'</div>').removeClass('hidden');
	}
	//password, repassword
	if($('[name=item]', form).val() == 'joinUserInfo'){
		if(!pass_el.val() || pass_el.val().length < 6){
			err_el.append('<div>* '+TVB.MError.pwd.illegal+'</div>').removeClass('hidden');
		}else if(pass_el.val() != repass_el.val()){
			err_el.append('<div>* '+TVB.MError.pwd.notmatch+'</div>').removeClass('hidden');
		}
	}
	if(!err_el.hasClass('hidden')){
		return false;
	}
	form.data('check', 0);
	jQuery.ajax({
		url: url,
		data: form.serialize(),
		dataType: 'json',
		type: form.attr('method'),
		success: function (data, status) {
			if(status != 'success'){
				err_el.append('<div>* '+TVB.MError.serverError+'</div>').removeClass('hidden');
				return false;
			}
			if(data.retFlag){
				form.data('check',1).submit();
			}else{
				if( !checkAjaxErrorCode(data.errCode, form) ){
					return false;
				}
				for(var i in data.errors){
					err_el.append('<div>'+data.errors[i]+'</div>').removeClass('hidden');
				}
			}
		},
		error: function (data) {
			err_el.append('<div>* '+TVB.MError.serverError+'</div>').removeClass('hidden');
		}
	});
	return false;
};
M.checkPayForm = function(){
	var form = $('#payForm'), mod=TVB.Mobile, url=$('.submit', form).attr('ajax'), oForm = form[0],
		card_owner = $('[name=card_owner]', form),
		card_no = $('[name=card_no]', form),
		card_cvv = $('[name=card_cvv]', form),
		agree_term = $('[name=agree_term]', form),
		captcha = $('[name=captcha]', form);
		err_el = $('.err-msg', form);
	err_el.html('').addClass('hidden');
	if(form.data('check')){
		return true;
	}
	if(card_owner.val() == ''){
		err_el.append('<div>* '+ TVB.MError.card_owner.empty +'</div>').removeClass('hidden');
	}
	if(card_no.val() == ''){
		err_el.append('<div>* '+ TVB.MError.card_no.empty +'</div>').removeClass('hidden');
	}else if(!mod.cardValid( card_no.val() )){
		err_el.append('<div>* '+ TVB.MError.card_no.invalid +'</div>').removeClass('hidden');
	}
	if(!card_cvv.val() || card_cvv.val().length != 3 || parseInt(card_cvv.val()) != card_cvv.val()){
		err_el.append('<div>* '+ TVB.MError.card_cvv.empty +'</div>').removeClass('hidden');
	}
	if( !mod.cardExpiryDate( $('[name=expiry_y]', form).val(), $('[name=expiry_m]', form).val(), 3) ){
		err_el.append('<div>* '+ TVB.MError.card_expiry.empty +'</div>').removeClass('hidden');
	}
	if(agree_term[0] && agree_term[0].checked === false){
		err_el.append('<div>* '+ TVB.MError.agree_term.empty +'</div>').removeClass('hidden');
	}
	if(captcha.val() == ''){
		err_el.append('<div>* '+ TVB.MError.captcha.empty +'</div>').removeClass('hidden');
	}
	if(!err_el.hasClass('hidden')) {
		return false;
	}
	form.data('saveing', 1).data('check', 0);
	jQuery.ajax({
		url: url,
		data: form.serialize(),
		dataType: 'json', 
		type: form.attr('method'),
		success: function (data, status) {
			form.data('saveing', 0);
			if(status != 'success'){
				err_el.append('<div>* '+TVB.MError.serverError+'</div>').removeClass('hidden');
				return false;
			}
			if(data.retFlag == 1){
				if(oForm.is_post_form && oForm.is_post_form.value == 0){
					window.location = oForm.successUrl.value +'&Ref='+data.data.order_ref;return false;
				}
				oForm.orderRef.value = data.data.order_ref;
				oForm.pMethod.value = $(oForm).find(':input[name=card_type]:checked').val();							
				oForm.epMonth.value = oForm.expiry_m.value;
				oForm.epYear.value = oForm.expiry_y.value;		
				oForm.securityCode.value = oForm.card_cvv.value;		
				oForm.cardHolder.value = oForm.card_owner.value;
				oForm.cardNo.value = oForm.card_no.value;
				form.data('check', 1).submit();
			}else{
				if( !checkAjaxErrorCode(data.errCode, form) ){
					return false;
				}
				for(var i in data.errors){
					err_el.append('<div>'+data.errors[i]+'</div>').removeClass('hidden');
				}
			}
		},
		error: function (data) {
			form.data('saveing', 0);
			err_el.append('<div>* '+TVB.MError.serverError+'</div>').removeClass('hidden');
		}
	});
	return false;
};
M.checkRegForm = function(){
	var form = $('#regForm'), url=$('#regForm .regbtn .btn').attr('ajax'),
		email_el = $('[name=email]', form),
		pass_el = $('[name=password]', form),
		repass_el = $('[name=repassword]', form),
		captcha = $('[name=captcha]', form),
		err_el = $('.err-msg', form);
	err_el.html('').addClass('hidden');
	if(!email_el.val()){
		err_el.append('<div>* '+TVB.MError.email.empty+'</div>').removeClass('hidden');
	}else if(!isValidEmail(email_el.val())){
		err_el.append('<div>* '+TVB.MError.email.illegal+'</div>').removeClass('hidden');
	}
	//password, repassword
	if(!pass_el.val() || pass_el.val().length < 6){
		err_el.append('<div>* '+TVB.MError.pwd.illegal+'</div>').removeClass('hidden');
	}else if(pass_el.val() != repass_el.val()){
		err_el.append('<div>* '+TVB.MError.pwd.notmatch+'</div>').removeClass('hidden');
	}
	if(captcha.val() == ''){
		err_el.append('<div>* '+ TVB.MError.captcha.empty +'</div>').removeClass('hidden');
	}
	if(!err_el.hasClass('hidden')){
		return false;
	}
	jQuery.ajax({
		url: url,
		data: form.serialize(),
		dataType: 'json',
		type: form.attr('method'),
		success: function (data, status) {
			if(status != 'success'){
				err_el.append('<div>* '+TVB.MError.serverError+'</div>').removeClass('hidden');
				return false;
			}
			if(data.retFlag){
				window.location = $('input[name=reback_url]', form).val();
			}else{
				if( !checkAjaxErrorCode(data.errCode, form) ){
					return false;
				}
				for(var i in data.errors){
					err_el.append('<div>'+data.errors[i]+'</div>').removeClass('hidden');
				}
			}
		},
		error: function (data) {
			err_el.append('<div>* '+TVB.MError.serverError+'</div>').removeClass('hidden');
		}
	});
	return false;
};
M.checkAgreeForm = function(){
	var form = $('#agreeForm'), mod=TVB.Mobile, url=$('#agreeForm .submit').attr('ajax'), oForm = form[0],
		agree_term = $('[name=agree_term]', form),
		captcha = $('[name=captcha]', form);
		err_el = $('.err-msg', form);
	err_el.html('').addClass('hidden');
	if(form.data('check')){
		return true;
	}
	if(agree_term[0] && agree_term[0].checked === false){
		err_el.append('<div>* '+ TVB.MError.agree_term.empty +'</div>').removeClass('hidden');
	}
	if(captcha.val() == ''){
		err_el.append('<div>* '+ TVB.MError.captcha.empty +'</div>').removeClass('hidden');
	}
	if(!err_el.hasClass('hidden')) {
		return false;
	}
	form.data('saveing', 1).data('check', 0);
	jQuery.ajax({
		url: url,
		data: form.serialize(),
		dataType: 'json', 
		type: form.attr('method'),
		success: function (data, status) {
			form.data('saveing', 0);
			if(status != 'success'){
				err_el.append('<div>* '+TVB.MError.serverError+'</div>').removeClass('hidden');
				return false;
			}
			if(data.retFlag == 1){
				oForm.orderRef.value = data.data.order_ref;
				form.data('check', 1).submit();
			}else{
				if( !checkAjaxErrorCode(data.errCode, form) ){
					return false;
				}
				for(var i in data.errors){
					err_el.append('<div>'+data.errors[i]+'</div>').removeClass('hidden');
				}
			}
		},
		error: function (data) {
			form.data('saveing', 0);
			err_el.append('<div>* '+TVB.MError.serverError+'</div>').removeClass('hidden');
		}
	});
	return false;
}

$(document).ready(function(){
	$('form').bind('submit', function(e){
		switch( $(this).attr('id') ){
			case 'loginForm':
				return M.checkLoginForm(); break;
			case 'uInfoForm':
				return M.checkUserInfoForm(); break;
			case 'payForm':
				return M.checkPayForm(); break;
			case 'regForm':
				return M.checkRegForm(); break;
			case 'agreeForm':
				return M.checkAgreeForm(); break;
			default: 
				return true; break;
		}
	});
	//$('a').attr('rel',"external");
	if($('body').attr('mlang')){
		TVB.MError = TVB.Error[$('body').attr('mlang')];
	}
	
	$('input.intel-text').each(function(){
		var el = $(this);
		if( el.attr('title')){
			el.bind('keyup', function(e){
				if(this.value){
					$(this).data('hasinput', 1);
				}
			}).bind('click', function(e){
				if(!$(this).data('hasinput')){
					this.value = '';
				}
			}).bind('focus', function(e){
				if(!$(this).data('hasinput')){
					this.value = '';
				}
			}).bind('blur', function(e){
				if(!$(this).data('hasinput')){
					this.value = $(this).attr('title');
				}
			}).val( el.attr('title') ).data('hasinput', 0);
		}
	});
	
});

$('#loginForm .skip').bind('click', function(e){
	window.location = $(this).attr('href');
});
$('#loginForm .login').bind('click', function(e){
	e.preventDefault();
	$('#loginForm').submit();
});
$('#login .jbtn').bind('click', function(e){
	e.preventDefault();
	$('#loginForm').submit();
});

$('#regForm .regbtn .btn').bind('click', function(e){
	e.preventDefault();
	$('#regForm').submit();
});

$('label').bind('click', function(e){
	var t = $('input', e.target);
	if(t.attr('type') == 'checkbox' || t.attr('type') == 'radio'){
		//t[0].checked = t[0].checked ? false : true;
	}
});

/*
** page information 
** bind: click "next"
*/
$('#uInfoForm .pn .next').bind('click', function(e){
	e.preventDefault();
	$('#uInfoForm').submit();
	//M.checkUserInfoForm();
});
/*
** page payment 
*/
$('#payForm .cancel').bind('click', function(e){return true;
	var form = $('#payForm');
	if(form.data('saveing')){
		e.preventDefault(); return false;
	}
	return true;
});
$('#payForm .clear, #agreeForm .clear').bind('click', function(e){
	e.preventDefault();
	var form = $(e.target).parents('form');
	if(form.data('saveing')){
		return false;
	}
	$('[name=card_type]', form).each(function(){
		if(this.value == 'VISA'){
			this.checked = true;
		}else{
			this.checked = false;
		}
	});
	$('[name=expiry_y]', form).val('');
	$('[name=expiry_m]', form).val('');
	$('[name=card_owner]', form).val('');
	$('[name=card_no]', form).val('');
	$('[name=card_cvv]', form).val('');
	$('[name=captcha]', form).val('');
});
$('#payForm .submit').bind('click', function(e){
	e.preventDefault();
	$('#payForm').submit();
});
/*
**  agreement page
*/
$('#agreeForm .submit').bind('click', function(e){
	e.preventDefault();
	$('#agreeForm').submit();
});
/*
** 
*/
$('#captcha-img, #reload-captcha-img').bind('click', function(e){
	$('#captcha-img')[0].src = './image.php?r=' + Math.random();
});
var isValidEmail = function (s) {
	var f=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
	return f.test(s) ? true:false;
};
var checkAjaxErrorCode = function(code, form){
	if(!form.length || form.length == 0){
		return false;
	}
	switch(code){
		case 1000:
			if($('input[name=restart_url]', form).length && $('input[name=restart_url]', form).val()){
				window.location = $('input[name=restart_url]', form).val(); return false;
			}
			break;
		case 1005:
			window.location = $('input[name=msgbox_url]', form).val(); return false;
			break;
		default :
			return true;
			break;
	}
}

//var jQT = new $.jQTouch();
//$('body').addClass('landscape').trigger('turn', {orientation: 'landscape'});